<?php
declare (strict_types = 1);
namespace app\course\logic\live;

use GuzzleHttp\Client;
use app\admin\logic\system\Config as SystemConfig;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Config;
use app\common\exception\LogicException;

/**
 * 声网接口类
 */
class Agora
{
    /**
     * 声网接口uri
     * @var string
     */
    protected $uri = "https://api.agora.io";

    /**
     * 声网配置appId
     * @var string
     */
    protected $appid = "";

    /**
     * 声网配置auth key:secret
     * @var string
     */
    protected $auth = "";

    /**
     * API接口名称
     * @var string
     */
    protected $api_name = '';

    /**
     * API接口path参数
     * @var array
     */
    protected $path_param = [];

    /**
     * API接口json参数
     * @var array
     */
    protected $json_param = [];

    /**
     * API接口query参数
     * @var array
     */
    protected $query_param = [];

    /**
     * API接口uri
     * @var string
     */
    protected $api_uri = '';

    /**
     * API接口请求方式
     * @var string
     */
    protected $request_type = '';

    /**
     * API接口header头
     * @var array
     */
    protected $headers = [];

    /**
     * 构造函数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     *
     * @param string $api_name [description]
     * @param array  $helpers  [description]
     */
    public function __construct($api_name = '', $helpers = [])
    {
        $config             = $this->get_agora_config();
        $this->appid        = $config['appid'];
        $this->auth         = $config['auth'];
        $this->api_name     = $api_name;
        $this->request_type = $this->get_request_type();
        $this->path_param   = $helpers['path_param'] ?? $this->path_param;
        $this->api_uri      = $this->get_api_uri();
        $this->json_param   = $helpers['json_param'] ?? $this->json_param;
        $this->query_param  = $helpers['query_param'] ?? $this->query_param;
        $this->headers      = $this->get_headers();

        return $this;
    }

    /**
     * send方法
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-29
     *
     * @return mixed [type]                      [description]
     * @throws GuzzleException
     */
    public function send()
    {

        $client = new Client();
        $param  = [
            'headers'       => $this->headers,
            'http_errors'   => false
        ];

        if (count($this->json_param)) $param['json'] = $this->json_param;
        if (count($this->query_param)) $param['query'] = $this->query_param;

        // return [$this->request_type, $this->api_uri, $param];

        $res        = $client->request( $this->request_type,  $this->api_uri, $param);
        $response   = $res->getBody()->getContents();
        $response   = json_decode($response);

        if ($response->code == 0) {
            return $response->data??$response;
        } else {
            throw new LogicException($response->msg);
        }
    }

    /**
     * 设置接口名称
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     * @param  [type]                      $api_name [description]
     */
    public function set_api_name($api_name)
    {
        $this->api_name     = $api_name;
        $this->request_type = $this->get_request_type();
        return $this;
    }

    /**
     * 设置接口path参数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     * @param  [type]                      $param [description]
     */
    public function set_path_param($param)
    {
        $this->path_param   = $param;
        $this->api_uri      = $this->get_api_uri();
        return $this;
    }

    /**
     * 设置接口json参数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     * @param  [type]                      $param [description]
     */
    public function set_json_param($param)
    {
        $this->json_param    = $param;
        return $this;
    }

    /**
     * 设置接口query参数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     * @param  [type]                      $param [description]
     */
    public function set_query_param($param)
    {
        $this->query_param    = $param;
        return $this;
    }

    /**
     * 添加header头
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     * @param  [type]                      $param [description]
     */
    public function add_headers($param)
    {
        $this->headers = array_merge($this->headers, $param);
        return $this;
    }

    /**
     * 获取api_uri
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     *
     * @return string [type]                      [description]
     */
    public function get_api_uri()
    {
        $api_uri = Config::get('agora.api.'.$this->api_name.'.api_uri');

        if ( false !== strstr($api_uri, "{appId}") ) {
            $api_uri = str_replace('{appId}', $this->appid, $api_uri);
        }

        if ( count($this->path_param) ) {
            foreach ($this->path_param as $key => $value) {
                // if ('key' == $key && is_array($value) ) {
                //     foreach ($value as $k => $v) {
                //         $api_uri = str_replace('{key}', $k, $api_uri);
                //         break;
                //     }
                // } else {
                    $api_uri = str_replace('{' . $key . '}', $value, $api_uri);
                // }
            }
        }

        $this->api_uri = $this->uri . $api_uri;

        return $this->api_uri;
    }

    /**
     * 获取接口请求方式
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     *
     * @return mixed [type]                      [description]
     */
    public function get_request_type()
    {
        return Config::get('agora.api.'.$this->api_name.'.request');
    }

    /**
     * 获取header头参数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     *
     * @return string[] [type]                      [description]
     */
    public function get_headers()
    {
        $headers = array(
            "Content-Type"  => "application/json",
            "Authorization" => " Basic " . base64_encode($this->auth)
        );

        if ( count($this->headers) ) {
            $headers = array_merge($headers, $this->headers);
        }

        return $headers;
    }

    /**
     * 获取声网后台配置
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-10-30
     *
     * @return array|mixed [type]                      [description]
     */
    public function get_agora_config()
    {
        $config = SystemConfig::get('course.live.config.agora', []);
        if ( empty($config) ) {
            throw new LogicException('服务暂不可用');
        }

        foreach ($config as &$val) {
            $val = trim($val, ' ');
        }
        unset($val);

        return $config;
    }
}
